package com.wskj.supermarket.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wskj.supermarket.pojo.UserInfo;
import com.wskj.supermarket.service.UserService;
import com.wskj.supermarket.service.impl.UserServiceImpl;

@WebServlet(urlPatterns={"/login.do"})
public class LoginServlet extends HttpServlet {
	private UserService  service=new UserServiceImpl();// 用户服务层
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		 
		req.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(req, resp);
	}
	
	
	
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		
		
		UserInfo  userInfo=service.getUserByNameAndPassword(username,password);
		
		
		if (userInfo!=null) {
			// 将用户保存到session 中
			req.getSession().setAttribute("user",userInfo);
			// 跳转到 主页
			resp.sendRedirect(req.getContextPath()+"/index.do");
		}else{
			
			// 登陆失败 
			req.setAttribute("error", "用户名或密码错误");
			
			req.getRequestDispatcher("/WEB-INF/page/login.jsp").forward(req, resp);
			
		}
		
		
		
		
	}
	
	
	

}
